/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */

import UIKit

//重用标记
private let EmoticonCollectionViewCellIdentifier = "EmoticonCollectionViewCellIdentifier"

class LSEmoticonKeyBoard: UIView {
    
    //MARK: - 懒加载控件
    private lazy var toolBar: LSEmoticonTooBar = {
        let toolBar = LSEmoticonTooBar(frame: CGRectZero)
        
        return toolBar
    }()
    
    //MARK: - 表情视图
    private lazy var emoticonCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        //设置水平方向移动
        flowLayout.scrollDirection = .Horizontal
        
        let view = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        view.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        //设置水平和垂直方向的滚动指示器不显示
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        //开启分页
        view.pagingEnabled = true
        //关闭弹簧效果
        view.bounces = false
        
        //注册cell
        view.registerClass(LSEmotionCollectionViewCell.self, forCellWithReuseIdentifier: EmoticonCollectionViewCellIdentifier)
        //数据源代理
        view.dataSource = self
        //设置代理
        view.delegate = self
        
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        //添加控件
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        
        //设置约束
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.height.equalTo(35)
        }
        
        toolBar.didSeletedButtonClosure = { [weak self] (type: LSEmoticonToolBarButtonType) in
            
            //滚动到indexPath
            let indexPath: NSIndexPath
            switch type {
            case .Normal:
                print("默认")
                indexPath = NSIndexPath(forItem: 0, inSection: 0)
            case .Emoji:
                print("emoji")
                indexPath = NSIndexPath(forItem: 0, inSection: 1)
            case .LXH:
                print("LXH")
                indexPath = NSIndexPath(forItem: 0, inSection: 2)
                
            }
            self?.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }
    
    //MARK: - 设置子控件布局方式
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //设置每项的大小
        flowLayout.itemSize = emoticonCollectionView.size
        //设置水平间距和垂直间距
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
    }
}

extension LSEmoticonKeyBoard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return LSEmoticonTools.sharedTools.allEmoticonArray.count 
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return LSEmoticonTools.sharedTools.allEmoticonArray[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCollectionViewCellIdentifier, forIndexPath: indexPath) as! LSEmotionCollectionViewCell
        //设置绑定数据
        cell.emoticons = LSEmoticonTools.sharedTools.allEmoticonArray[indexPath.section][indexPath.item]
        
        return cell
    }
    
    //MARK: - 监听collectionView的滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //获取当前屏幕显示的cell,获取的cell不会对其进行x坐标排序,随机返回的
        let cells = emoticonCollectionView.visibleCells().sort { (firstCell, secondCell) -> Bool in
            return firstCell.x < secondCell.x
        }
        
        //判断哪个cell显示多
        if cells.count == 2 {
            //获取第一个cell
            let firstCell = cells.first!
            //获取第二个cell
            let secondCell = cells.last!
            //print("第一个cell: \(firstCell)")
            //print("第二个cell: \(secondCell)")
            
            //通过差值的计算,判断哪个cell显示多
            //第一个偏移量差值(只关心便宜的差值多少)
            let firstContentOffSetX = abs(firstCell.x - scrollView.contentOffset.x)
            //第二个偏移量差值
            let secondContentOffSetX = secondCell.x - scrollView.contentOffset.x
            //print("第一个差值\(firstContentOffSetX)")
            //print("第二个差值\(secondContentOffSetX)")
            
            
            //记录哪个cell显示的多
            let cell: UICollectionViewCell
            if firstContentOffSetX < secondContentOffSetX {
                //print("第一个cell显示多")
                cell = firstCell
            } else {
                //print("第二个cell显示多")
                cell = secondCell
            }
            
            //根据cell获取对应的indexPath
            let indexPath = emoticonCollectionView.indexPathForCell(cell)!
            //获取indexPath对应的是哪个一组
            let section = indexPath.section
            
            //选中制定这组数据
            toolBar.selectedButtonWithSection(section)
        }
    }
}



















